<template>
  <el-dialog 
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="900px"
    @close="resetForm">
    <el-form 
      ref="goodsForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      label-position="right">
      
      <!-- 基础信息 -->
      <el-row :gutter="30">
        <!-- 左列 -->
        <el-col :span="12">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称"/>
          </el-form-item>

          <el-form-item label="副标题" prop="subname">
            <el-input 
              v-model="form.subname"
              type="textarea"
              :rows="2"
              placeholder="请输入商品副标题"/>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input-number 
              v-model="form.price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"/>
          </el-form-item>
        </el-col>

        <!-- 右列 -->
        <el-col :span="12">
          <el-form-item label="封面图" prop="coverPic">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="handleCoverSuccess">
              <img v-if="form.coverPic" :src="form.coverPic" class="upload-cover">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>

          <el-form-item label="社区ID" prop="communityId">
            <el-select
              v-model="form.communityId"
              placeholder="请选择社区"
              filterable>
              <el-option
                v-for="item in communities"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="商品类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio :label="1">福利商品</el-radio>
              <el-radio :label="2">生活商品</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="上架状态" prop="onSale">
            <el-switch
              v-model="form.onSale"
              :active-value="0"
              :inactive-value="1"
              active-text="上架"
              inactive-text="下架"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 支付方式 -->
      <el-form-item label="支持支付" prop="supportPoint">
        <el-switch
              v-model="form.supportPoint"
              :active-value="0"
              :inactive-value="1"
              active-text="人民币"
              inactive-text="积分"/>
        <!-- <el-checkbox-group v-model="form.supportPoint">
          <el-checkbox :label="0">人民币</el-checkbox>
          <el-checkbox :label="1">积分</el-checkbox>
        </el-checkbox-group> -->
      </el-form-item>

      <!-- 轮播图管理 -->
      <div class="image-section">
        <h4 class="section-title">轮播图管理（类型1）</h4>
        <div 
          v-for="(item, index) in form.lbPicList"
          :key="index"
          class="image-item">
          <el-form-item
            label="轮播图"
            :prop="`lbPicList.${index}.picAddress`"
            :rules="picRules">
            <el-upload
              class="image-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="(res) => handleUploadSuccess(res, 'lbPicList', index)">
              <img v-if="item.picAddress" :src="item.picAddress" class="upload-image">
              <i v-else class="el-icon-plus image-uploader-icon"/>
            </el-upload>
          </el-form-item>
          
          <el-form-item 
            label="排序"
            :prop="`lbPicList.${index}.sort`"
            class="sort-input">
            <el-input-number 
              v-model="item.sort"
              :min="1"
              controls-position="right"/>
          </el-form-item>

          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeImage('lbPicList', index)"/>
        </div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addImage('lbPicList')">
          添加轮播图
        </el-button>
      </div>

      <!-- 详情图管理 -->
      <div class="image-section">
        <h4 class="section-title">详情图管理（类型2）</h4>
        <div 
          v-for="(item, index) in form.detailPicList"
          :key="index + 100"
          class="image-item">
          <el-form-item
            label="详情图"
            :prop="`detailPicList.${index}.picAddress`"
            :rules="picRules">
            <el-upload
              class="image-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="(res) => handleUploadSuccess(res, 'detailPicList', index)">
              <img v-if="item.picAddress" :src="item.picAddress" class="upload-image">
              <i v-else class="el-icon-plus image-uploader-icon"/>
            </el-upload>
          </el-form-item>

          <el-form-item 
            label="排序"
            :prop="`detailPicList.${index}.sort`"
            class="sort-input">
            <el-input-number 
              v-model="item.sort"
              :min="1"
              controls-position="right"/>
          </el-form-item>

          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeImage('detailPicList', index)"/>
        </div>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addImage('detailPicList')">
          添加详情图
        </el-button>
      </div>
        <el-form-item label="内容">
          <!-- <el-input v-model="dataForm.text" placeholder="内容"></el-input> -->
          <quill-editor v-model="content" :options="quillConfig"></quill-editor>
          <!-- <quill-editor style="height: 500px; overflow-y: hidden;"
            v-model="content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated" /> -->
        </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
      import quillConfig from '@/utils/quillConfig'
export default {
  data() {
    // 自定义验证规则
    const validatePrice = (rule, value, callback) => {
      if (value === null || value === undefined) {
        callback(new Error('请输入商品价格'));
      } else if (value < 0) {
        callback(new Error('价格不能为负数'));
      } else {
        callback();
      }
    };

    return {
      content: '<p>hello</p>',
      url:'',
      dialogVisible: false,
      dialogTitle: '新建商品',
      form: {
        name: '',
        coverPic: '',
        price: null,
        subname: '',
        supportPoint: '',
        type: 1,
        onSale: 0,
        communityId: '',
        lbPicList: [],
        detailPicList: []
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [{ validator: validatePrice, trigger: 'blur' }],
        communityId: [{ required: true, message: '请选择社区', trigger: 'change' }],
        // supportPoint: [
        //   { type: 'array', required: true, message: '至少选择一种支付方式', trigger: 'change' }
        // ]
      },
      picRules: [
        { required: true, message: '请上传图片', trigger: 'change' }
      ],
      communities: [] // 从接口获取
    }
  },
  methods: {
    init(id) {
      this.quillConfig = quillConfig
      this.dialogVisible = true
      this.communitiesList();
      this.url = this.$http.adornUrl(
        `app/oss/upload?token=${this.$cookie.get("token")}`
      );
      if(id) {
        this.$http({
            url: this.$http.adornUrl(
              `yshbms/goods/info/${id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.form = data.communityEntity
              this.content = data.communityEntity.goodsDetail
              console.log(data,'datadatadatadatadata')
            }
          });
      }
    },
    // 打开弹窗
    openDialog() {
      this.dialogVisible = true
    },
    communitiesList() {
      this.$http({
        url: this.$http.adornUrl("yshbms/community/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.communities = data.page.list;
        } else {
          this.communities = [];
        }
      });
        this.$http({
          url: this.$http.adornUrl(`yshbms/goods/list`),
          method: "post",
          data: this.$http.adornData()
        }).then(({ data }) => {
            if (data && data.code === 0) {
          this.goodsList = data.page.list;
        } else {
          this.goodsList = [];
        }
        });
    },
    // 上传成功处理
    handleCoverSuccess(res) {
      console.log(res)
      this.form.coverPic ='https://yunchenbucket.oss-cn-qingdao.aliyuncs.com/' + res.url
    },

    handleUploadSuccess(res, type, index) {
      this.form[type][index].picAddress ='https://yunchenbucket.oss-cn-qingdao.aliyuncs.com/'+ res.url
    },

    // 图片项管理
    addImage(type) {
      this.form[type].push({
        picAddress: '',
        type: type === 'lbPicList' ? 1 : 2,
        sort: this.form[type].length + 1
      })
    },

    removeImage(type, index) {
      this.form[type].splice(index, 1)
    },

    // 表单提交
    submitForm() {
      this.$refs.goodsForm.validate(valid => {
        const formData = {
            ...this.form,
            // 自动填充当前时间相关字段
          }
          formData.goodsDetail = this.content
        if (valid) {
          if(this.form.id) {
            this.$http({
              url: this.$http.adornUrl(`yshbms/goods/update`),
              method: "post",
              data: this.$http.adornData(formData)
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.$emit("refreshDataList");
                    this.dialogVisible = false
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            this.$http({
              url: this.$http.adornUrl(`yshbms/goods/save`),
              method: "post",
              data: this.$http.adornData(formData)
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.$emit("refreshDataList");
                    this.dialogVisible = false
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
         
          console.log('提交数据1:', formData)
          
          this.dialogVisible = false
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.goodsForm.resetFields()
      this.form.lbPicList = []
      this.form.detailPicList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader, .image-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409EFF;
    }
  }
}

.upload-cover {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: contain;
}

.image-section {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  .section-title {
    color: #606266;
    margin-bottom: 15px;
  }
}

.image-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  .image-uploader {
    margin-right: 15px;
    .upload-image {
      width: 120px;
      height: 120px;
      object-fit: contain;
    }
  }
  .sort-input {
    width: 100px;
    margin: 0 15px;
  }
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
</style>
